<template>
  <el-dialog
    v-model="visible"
    title="选择监听器"
    width="60%"
  >
    <div class="listener-selector">
      <!-- 搜索框 -->
      <div class="search-bar">
                <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
                <el-form-item label="监听器名称" prop="name">
                    <el-input
                    v-model="queryParams.name"
                    placeholder="请输入流程名称"
                    clearable
                    @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
                </el-form>
      </div>
      
      <!-- 监听器列表 -->
      <div class="list-container">
        <el-table
          :data="listenerList"
          height="400px"
          highlight-current-row
          v-loading="loading"  @selection-change="handleSelectionChange" border
        >
          <!-- <el-table-column label="选择" width="60">
            <template #default="{ row }">
              <el-radio v-model="selectedId" :label="row.id">&nbsp;</el-radio>
            </template>
          </el-table-column> -->
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="监听器名称" prop="name" width="200" />
          <el-table-column label="事件类型" width="180">
            <template #default="{ row }">
              <el-select v-model="row.event" placeholder="请选择事件">
                <el-option
                  v-for="event in row.events"
                  :key="event"
                  :label="event"
                  :value="event"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="描述" prop="description" show-overflow-tooltip />
        </el-table>
        
        <!-- 分页控件 -->
        <div class="pagination">
          <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
                />
        </div>


      </div>
      
      <!-- 底部按钮 -->
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelection">确定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import {API_PROCESS_LISTENER} from '@/api/workflow/bpmnProcessListener.ts'
import { usePlugins } from '@/plugins'
const plugins = usePlugins()

const props = defineProps({
  visible: Boolean,
  listenerType: String // execution, task等
})

//父组件调用的方法，visible是v-mode冒号后面的，
const emit = defineEmits(['update:visible', 'select'])

// 控制弹窗显示
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})


const loading = ref(true)
const showSearch = ref(true) //是否展示搜索
const selectedListeners = ref([]) //多选后的id
const single = ref(true) //单选
const multiple = ref(true) //多选
const total = ref(0)


const data = reactive({
    
    queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    listenerType:'',
  },
});

const { queryParams } = toRefs(data)
const listenerList = ref([]);




// 加载监听器数据（模拟API请求）
const getList = () => {
    queryParams.listenerType = props.listenerType
    loading.value = true
    API_PROCESS_LISTENER.getProcessListenerPage(queryParams.value).then(response => {
        listenerList.value = response.rows
        total.value = response.total
        loading.value = false
  })

}

// 初始化加载监听器
onMounted(async () => {
  getList()
})


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  
  getList()
}



// 监听器数据
const allListeners = ref([])
// 根据搜索文本过滤监听器,这是用前端的进行搜索
const filteredListeners = computed(() => {
  if (!searchText.value) return allListeners.value
  
  return allListeners.value.filter(listener => 
    listener.name.includes(searchText.value) || 
    listener.description.includes(searchText.value)
  )
})



// 搜索优化（防抖）
const onSearch = () => {
  clearTimeout(timer.value)
  timer.value = setTimeout(() => {
    currentPage.value = 1 // 重置到第一页
  }, 300)
}

// 行点击事件
const onRowClick = (row) => {
  selectedId.value = row.id
  selectedEvent.value = row.events?.[0] || 'start'
}


// 多选框选中数据
function handleSelectionChange(selection) {

    selectedListeners.value = selection
    single.value = selection.length != 1
    multiple.value = !selection.length
}


/** 选择多个监听器，然后放进去 */
function confirmSelectionPlus(row) {
  let returnData = [];
  if (row) {
    // 单个行点击 - 包装成数组
    returnData = [row];
  } else if (selectedListeners.value && selectedListeners.value.length > 0) {
    // 勾选的行 - 已经是数组
    returnData = [...selectedListeners.value];
  }
  if (returnData) {
    emit('select', returnData)
    visible.value = false
  }
}

// 确认选择
const confirmSelection = () => {
  if (!selectedId.value) {
    plugins.$modal.msgError('请先选择一个监听器')
    return
  }
  
  const selected = allListeners.value.find(
    listener => listener.id === selectedId.value
  )
  
  if (selected) {
    selected.event = selectedEvent.value
    emit('select',props.listenerType, selected)
    visible.value = false
  }
}
</script>

<style scoped>
.listener-selector {
  padding: 10px;
}

.search-bar {
  margin-bottom: 15px;
}

.list-container {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>